package org.daochong.web;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.daochong.lang.StringUtils;

public class DefaultResourcesGroupLoader {

	private static DefaultResourcesGroupLoader INSTANCE;

	public static String ENCODING = null;

	public static String DEFAULT_PATH = "/resources/loader";

	private static String PATH;

	public static String getPath() {
		try {
			URL url = DefaultResourcesGroupLoader.class.getResource(DEFAULT_PATH);
			if (url != null) {
				PATH = url.getFile();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return PATH;
	}

	private Map<String, FileCache> map = new LinkedHashMap<String, FileCache>();

	public static DefaultResourcesGroupLoader getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new DefaultResourcesGroupLoader();
		}
		return INSTANCE;
	}

	public Set<String> loadAll(String group, Locale locale, String skin) {
		FileCache cache = map.get(group);
		if (cache != null) {
			File f = new File(cache.getPath());
			if (f.lastModified() > cache.getLast()) {
				cache.setFiles(toFiles(f));
			}
			return cache.getFiles();
		} else {
			String path = getPath() + "/" + group + ".properties";
			File file = new File(path);
			if (file.exists()) {
				cache = new FileCache();
				map.put(group, cache);
				cache.setGroup(group);
				cache.setPath(path);
				cache.setLast(System.currentTimeMillis());
				cache.setFiles(toFiles(file));
				return cache.getFiles();
			}
		}
		return new LinkedHashSet<String>();
	}

	private Set<String> toFiles(File file) {
		String str = null;
		try {
			if (ENCODING == null) {
				str = StringUtils.toString(new FileInputStream(file));
			} else {
				str = StringUtils.toString(new FileInputStream(file), ENCODING);
			}
			String[] ar = str.split("\r\n");
			Set<String> files = new LinkedHashSet<String>();
			for (String s : ar) {
				s = s.trim();
				if (s.startsWith("#"))
					continue;
				files.add(s);
			}
			return files;
		} catch (Throwable e) {
			e.printStackTrace();
		}
		return null;
	}

}

class FileCache {
	private String group;
	private String path;
	private long last;
	private Set<String> files;

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getGroup() {
		return group;
	}

	public void setGroup(String group) {
		this.group = group;
	}

	public long getLast() {
		return last;
	}

	public void setLast(long last) {
		this.last = last;
	}

	public Set<String> getFiles() {
		return files;
	}

	public void setFiles(Set<String> files) {
		this.files = files;
	}

}
